const arr = [1, 2, 3, 3, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 8, 8, 9, 9];

function find(array, first, last, k) {
  const firstIndex = getFirst(array, first, last, k);
  const lastIndex = getLast(array, first, last, k);
  if (lastIndex - firstIndex >= 0) {
    return lastIndex - firstIndex + 1;
  }
  return 0;
}
function getFirst(array, first, last, k) {
  if (first > last) return -1;
  const mid = Math.floor((first + last) / 2);
  if (array[mid] > k) {
    return getFirst(array, first, mid - 1, k);
  } else if (array[mid] < k) {
    return getFirst(array, mid + 1, last, k);
  } else {
    if (array[mid - 1] !== k) {
      return mid;
    }
    return getFirst(array, first, mid - 1, k);
  }
}
function getLast(array, first, last, k) {
  if (first > last) return -1;
  const mid = Math.floor((first + last) / 2);
  if (array[mid] > k) {
    return getLast(array, first, mid - 1, k);
  } else if (array[mid] < k) {
    return getLast(array, mid + 1, last, k);
  } else {
    if (array[mid + 1] !== k) {
      return mid;
    }
    return getLast(array, mid - 1, last, k);
  }
}

console.log(find(arr, 0, arr.length, 6))